﻿using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web.UI;
using ArchivingDataModel;
using ArchivingDataWebForms.Helpers;
using CommunicationManagementBusinessLayer;

namespace ArchivingDataWebForms.Pages.Import
{
    public partial class Import : WebFormBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this.getOrganizations();
            }
        }

        private void getOrganizations()
        {
            using (CommunicationManagementEntities entities = new CommunicationManagementEntities())
            {
                var orgs = entities.Organizations.Where(i => i.Is_External == 0 && i.ParentOrganization==null);
                foreach (var item in orgs)
                {
                    this.RadTreeViewOrganization.Nodes.Add(new Telerik.Web.UI.RadTreeNode()
                    {
                        Text=item.Organization_Name_AR,
                        Value=item.Organization_ID.ToString(),
                        ExpandMode=Telerik.Web.UI.TreeNodeExpandMode.ServerSide
                    });
                }
            }
        }

        //protected void RadButtonImportLocalNetwork_Click(object sender, EventArgs e)
        //{
        //    if (!string.IsNullOrEmpty(this.RadTextBoxServer.Text))
        //    {
        //        try
        //        {
        //            using (ArchivingDataEntities ent = new ArchivingDataEntities())
        //            {
        //                using (PathHelper path = new PathHelper(this.RadTextBoxServer.Text, "", this.RadTextBoxUser.Text, this.RadTextBoxPassword.Text))
        //                {
        //                   string id= this.importNetWorkDirectory(path.FullPath,ent,null);
        //                    ScriptManager.RegisterStartupScript(this, this.GetType(), "RefreshParentTree", "window.parent.RefreshFolderTree('" + id + "')", true);
        //                }
        //            }
        //            this.ShowNotification("تم الاستيراد" , NotificationIconType.Ok);
        //        }
        //        catch(Exception err)
        //        {
        //            this.ShowNotification("حدث الخطا التالي اثناء عملية الاستيراد" + err.Message, NotificationIconType.Error);
        //        }
        //    }
        //}

        private string importNetWorkDirectory(string fullPath, ArchivingDataEntities ent, long? parentID)
        {
            string DirectoryID = "";
            //import him self
            Folder newFolder = new Folder()
            {
                Folder_Code = "",
                ParentFolder_ID = parentID,
                Folder_Order = ent.Folders.Where(i=>i.ParentFolder_ID==parentID).Count()+1,
                FolderName_Ar = new DirectoryInfo(fullPath).Name,
                FolderNote_Ar = "Imported Folder :" + new DirectoryInfo(fullPath).Name,
                Is_RecycleBin = false,
                FilesType = ent.FilesTypes.FirstOrDefault(),
                ImagePath=CustomAppSettings.DefaultFolderImagePath
            };
            newFolder.Folder_UniqueText = WebHelper.Helpers.StringHelper.ToUniqueStatement(newFolder.Folder_Code + newFolder.FolderName_Ar + newFolder.FolderNote_Ar + newFolder.FolderNote_Ar + newFolder.FolderNote_En);
            ent.AddToFolders(newFolder);
            ent.SaveChanges();

            //files
            string[] files = Directory.GetFiles(fullPath);
            for (int i = 0; i < files.Length; i++)
            {
                ArchivingDataModel.File newFile = new ArchivingDataModel.File()
                {
                    Folder = newFolder,
                    File_Code = "",
                    File_Order = newFolder.Files.Count() + 1,
                    FileTitle_Ar = Path.GetFileNameWithoutExtension(files[i]),
                    FileTitle_En = Path.GetFileNameWithoutExtension(files[i]),
                    FileSubject_Ar = Path.GetFileNameWithoutExtension(files[i]),
                    FileSubject_En = Path.GetFileNameWithoutExtension(files[i]),
                    FileNote_Ar ="Imported File :"+ Path.GetFileName(files[i]),
                    FileNote_En ="Imported File :" + Path.GetFileName(files[i]),
                    FromDate = null,
                    ToDate = null,
                    Is_RecycleBin = false
                };
                newFile.File_UniqueText = WebHelper.Helpers.StringHelper.ToUniqueStatement(newFile.File_Code + newFile.FileTitle_Ar + newFile.FileTitle_En + newFile.FileSubject_Ar + newFile.FileSubject_En + newFile.FileNote_Ar + newFile.FileNote_En);
                ent.AddToFiles(newFile);
                ent.SaveChanges();

                //attachment
                ArchivingDataModel.Attachment newAttachment = new ArchivingDataModel.Attachment
                {
                    Attachment_Order = 1,
                    Attachment_Code = "",
                    AttachmentTitle_Ar = newFile.FileTitle_Ar,
                    AttachmentNote_Ar = newFile.FileTitle_Ar,
                };
                newAttachment.Attachment_UniqueText = WebHelper.Helpers.StringHelper.ToUniqueStatement(newAttachment.AttachmentTitle_Ar + newAttachment.AttachmentTitle_En + newAttachment.AttachmentNote_Ar + newAttachment.AttachmentNote_En);
                newFile.Attachments.Add(newAttachment);
                ent.SaveChanges();
                string imagePath = CustomAppSettings.DefaultFileImagePath;
                string datePath = DateTime.Now.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);
                imagePath = CustomAppSettings.FilesPathes + "/" + datePath + "/" + newAttachment.Attachment_ID + Path.GetExtension(files[i]);
                Directory.CreateDirectory(Path.GetDirectoryName(CustomAppSettings.getActualPath(imagePath)));
                System.IO.File.Copy(files[i], CustomAppSettings.getActualPath(imagePath));
                newAttachment.Attachment_Path = imagePath;
                newAttachment.MimeType = "application/octet-stream";
                if (files[i].ToLower().EndsWith(".jpg") || files[i].ToLower().EndsWith(".jpeg"))
                {
                    newAttachment.MimeType = "image/jpeg";
                }
                if (files[i].ToLower().EndsWith(".png"))
                {
                    newAttachment.MimeType = "png";
                }
                if (files[i].ToLower().EndsWith(".gif"))
                {
                    newAttachment.MimeType = "gif";
                }
                ent.SaveChanges();

            }

            //subdirectories
            string[] subDirectories = Directory.GetDirectories(fullPath);
            for (int i = 0; i < subDirectories.Length;i++)
            {
                this.importNetWorkDirectory(subDirectories[i], ent, newFolder.Folder_ID);
            }
            return DirectoryID;
        }

        protected void RadBUttonInportFromCommunication_Click(object sender, EventArgs e)
        {
            using (CommunicationManagementEntities comEntities = new CommunicationManagementEntities())
            {
                using (ArchivingDataEntities entities = new ArchivingDataEntities())
                {
                    if (this.RadComboBoxTreatementType.SelectedValue == "wared")
                    {
                        if (!string.IsNullOrEmpty(this.RadTreeViewOrganization.SelectedValue))
                        {
                            long OrgID = Convert.ToInt64(this.RadTreeViewOrganization.SelectedValue);
                            OrgID = comEntities.Organizations.Include("ParentOrganization").FirstOrDefault(i => i.Organization_ID == OrgID).StandAloneOrganization.Organization_ID;
                            IQueryable<Wared> wards = comEntities.Wareds.Include("Sader.Document.Attachments.AttachmentsParts").Where(i => i.Organization.Organization_ID == OrgID);
                            if (this.RadNumericTextBoxFrom.Value.HasValue)
                            {
                                wards = wards.Where(i => i.GeneratedNumber >= this.RadNumericTextBoxFrom.Value);
                            }
                            if (this.RadNumericTextBoxTo.Value.HasValue)
                            {
                                wards = wards.Where(i => i.GeneratedNumber <= this.RadNumericTextBoxTo.Value);
                            }
                            if (this.AdvancedDateTimePickerFrom.SelectedDate.HasValue)
                            {
                                DateTime datefrom = this.AdvancedDateTimePickerFrom.SelectedDate.Value.Date;
                                wards = wards.Where(i => i.EntryDate >= datefrom);
                            }
                            if (this.AdvancedDateTimePickerTo.SelectedDate.HasValue)
                            {
                                DateTime dateTo = this.AdvancedDateTimePickerTo.SelectedDate.Value.Date.AddDays(1);
                                wards = wards.Where(i => i.EntryDate < dateTo);
                            }
                            foreach (var item in wards)
                            {
                                string fileCode="w_" + item.Wared_ID;
                                var file = new ArchivingDataModel.File();
                                if (file == null)
                                {
                                    file = new ArchivingDataModel.File();
                                }
                                long folderid = Convert.ToInt64(this.Request.QueryString[QueryStringParams.Folder_ID]);
                                file.Folder = entities.Folders.FirstOrDefault(i => i.Folder_ID == folderid);
                                file.FileTitle_Ar = "وارد رقم" + item.Wared_Number;
                                file.FileSubject_Ar = item.Sader.Document.SubjectText;
                                file.FromDate = item.EntryDate;
                                file.File_Code = "w_" + item.Wared_ID;
                                file.Is_RecycleBin = false;
                                file.File_UniqueText = WebHelper.Helpers.StringHelper.ToUniqueStatement(file.File_Code + file.FileTitle_Ar + file.FileTitle_En + file.FileSubject_Ar + file.FileSubject_En + file.FileNote_Ar + file.FileNote_En);
                                if (file.File_ID == 0)
                                {
                                    entities.AddToFiles(file);
                                }
                                var attachmentParts=wards.SelectMany(i=>i.Sader.Document.Attachments).SelectMany(i=>i.AttachmentsParts);
                                entities.SaveChanges();
                                foreach (var subItem in attachmentParts)
                                {
                                    string fullPath = subItem.getFullPath(comEntities);


                                    string code = file.File_Code;
                                    string titleAr = file.FileTitle_Ar;
                                    string noteAr = file.FileNote_Ar;
                                    string uniquetext = WebHelper.Helpers.StringHelper.ToUniqueStatement(code + titleAr + noteAr);
                                    int order = file.Attachments.Count() + 1;
                                    ArchivingDataModel.Attachment attitem = new ArchivingDataModel.Attachment
                                    {
                                        Attachment_Order = order,
                                        Attachment_Code = code,
                                        AttachmentTitle_Ar = titleAr,
                                        AttachmentNote_Ar = noteAr,
                                        Attachment_UniqueText = uniquetext
                                    };
                                    file.Attachments.Add(attitem);
                                    entities.SaveChanges();
                                    string imagePath = CustomAppSettings.DefaultFileImagePath;
                                    string datePath = DateTime.Now.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);
                                    imagePath = CustomAppSettings.FilesPathes + "/" + datePath + "/" + attitem.Attachment_ID + Path.GetExtension(fullPath);
                                    Directory.CreateDirectory(Path.GetDirectoryName(CustomAppSettings.getActualPath(imagePath)));
                                    if (!System.IO.File.Exists(fullPath))
                                    {
                                        this.ShowNotification("لايوجد ملف", NotificationIconType.Warning);
                                        continue;
                                    }
                                    System.IO.File.Copy(fullPath, CustomAppSettings.getActualPath(imagePath));

                                    attitem.Attachment_Path = imagePath;
                                    attitem.MimeType = null;
                                    if (attitem.MimeType == null)
                                    {
                                        attitem.MimeType = WebHelper.Helpers.MimeTypeHelper.getMimeFromExtension(Path.GetExtension(fullPath));
                                        if (attitem.MimeType == null)
                                        {
                                            attitem.MimeType = WebHelper.Helpers.MimeTypeHelper.getMimeFromFile(CustomAppSettings.getActualPath(imagePath));
                                        }
                                    }
                                    entities.SaveChanges();
                                }
                            }
                        }
                        else
                        {
                            this.ShowNotification("من فضلك اختر احد الجهات", NotificationIconType.Warning);
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(this.RadTreeViewOrganization.SelectedValue))
                        {
                            long OrgID = Convert.ToInt64(this.RadTreeViewOrganization.SelectedValue);
                            OrgID = comEntities.Organizations.Include("ParentOrganization").FirstOrDefault(i => i.Organization_ID == OrgID).StandAloneOrganization.Organization_ID;
                            IQueryable<Sader> saders = comEntities.Saders.Include("Document.Attachments.AttachmentsParts").Where(i => i.Organization.Organization_ID == OrgID);
                            if (this.RadNumericTextBoxFrom.Value.HasValue)
                            {
                                saders = saders.Where(i => i.GeneratedNumber >= this.RadNumericTextBoxFrom.Value);
                            }
                            if (this.RadNumericTextBoxTo.Value.HasValue)
                            {
                                saders = saders.Where(i => i.GeneratedNumber <= this.RadNumericTextBoxTo.Value);
                            }
                            if (this.AdvancedDateTimePickerFrom.SelectedDate.HasValue)
                            {
                                DateTime datefrom = this.AdvancedDateTimePickerFrom.SelectedDate.Value.Date;
                                saders = saders.Where(i => i.EntryDate >= datefrom);
                            }
                            if (this.AdvancedDateTimePickerTo.SelectedDate.HasValue)
                            {
                                DateTime dateTo = this.AdvancedDateTimePickerTo.SelectedDate.Value.Date.AddDays(1);
                                saders = saders.Where(i => i.EntryDate < dateTo);
                            }
                            foreach (var item in saders)
                            {
                                string fileCode = "s_" + item.Sader_ID;
                                var file = new ArchivingDataModel.File();
                                if (file == null)
                                {
                                    file = new ArchivingDataModel.File();
                                }
                                long folderid = Convert.ToInt64(this.Request.QueryString[QueryStringParams.Folder_ID]);
                                file.Folder = entities.Folders.FirstOrDefault(i => i.Folder_ID == folderid);
                                file.FileTitle_Ar = "صادر رقم" + item.Sader_Number;
                                file.FileSubject_Ar = item.Document.SubjectText;
                                file.FromDate = item.EntryDate;
                                file.File_Code = "s_" + item.Sader_ID;
                                file.Is_RecycleBin = false;
                                file.File_UniqueText = WebHelper.Helpers.StringHelper.ToUniqueStatement(file.File_Code + file.FileTitle_Ar + file.FileTitle_En + file.FileSubject_Ar + file.FileSubject_En + file.FileNote_Ar + file.FileNote_En);
                                if (file.File_ID == 0)
                                {
                                    entities.AddToFiles(file);
                                }
                                var attachmentParts = saders.SelectMany(i => i.Document.Attachments).SelectMany(i => i.AttachmentsParts);
                                entities.SaveChanges();
                                foreach (var subItem in attachmentParts)
                                {
                                    string fullPath = subItem.getFullPath(comEntities);


                                    string code = file.File_Code;
                                    string titleAr = file.FileTitle_Ar;
                                    string noteAr = file.FileNote_Ar;
                                    string uniquetext = WebHelper.Helpers.StringHelper.ToUniqueStatement(code + titleAr + noteAr);
                                    int order = file.Attachments.Count() + 1;
                                    ArchivingDataModel.Attachment attitem = new ArchivingDataModel.Attachment
                                    {
                                        Attachment_Order = order,
                                        Attachment_Code = code,
                                        AttachmentTitle_Ar = titleAr,
                                        AttachmentNote_Ar = noteAr,
                                        Attachment_UniqueText = uniquetext
                                    };
                                    file.Attachments.Add(attitem);
                                    entities.SaveChanges();
                                    string imagePath = CustomAppSettings.DefaultFileImagePath;
                                    string datePath = DateTime.Now.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);
                                    imagePath = CustomAppSettings.FilesPathes + "/" + datePath + "/" + attitem.Attachment_ID + Path.GetExtension(fullPath);
                                    Directory.CreateDirectory(Path.GetDirectoryName(CustomAppSettings.getActualPath(imagePath)));
                                    if (!System.IO.File.Exists(fullPath))
                                    {
                                        this.ShowNotification("لايوجد ملف", NotificationIconType.Warning);
                                        continue;
                                    }
                                    System.IO.File.Copy(fullPath, CustomAppSettings.getActualPath(imagePath));

                                    attitem.Attachment_Path = imagePath;
                                    attitem.MimeType = null;
                                    if (attitem.MimeType == null)
                                    {
                                        attitem.MimeType = WebHelper.Helpers.MimeTypeHelper.getMimeFromExtension(Path.GetExtension(fullPath));
                                        if (attitem.MimeType == null)
                                        {
                                            attitem.MimeType = WebHelper.Helpers.MimeTypeHelper.getMimeFromFile(CustomAppSettings.getActualPath(imagePath));
                                        }
                                    }
                                    entities.SaveChanges();
                                }
                            }
                        }
                        else
                        {
                            this.ShowNotification("من فضلك اختر احد الجهات", NotificationIconType.Warning);
                        }
                    }
                }
            }
            ScriptManager.RegisterStartupScript(this, this.GetType(), "RefreshParentTree", "window.parent.RefreshFolderTree('" + this.Request.QueryString[QueryStringParams.Folder_ID] + "')", true);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Redirect", "Redirect('" + WebHelper.Helpers.UrlHelper.GetCompleteUri( "~/pages/Files/ViewFiles.aspx?" + QueryStringParams.Folder_ID + "=" + this.Request.QueryString[QueryStringParams.Folder_ID]) + "',1000)", true);
        }

        protected void RadTreeViewOrganization_NodeExpand(object sender, Telerik.Web.UI.RadTreeNodeEventArgs e)
        {
            using (CommunicationManagementEntities entities = new CommunicationManagementEntities())
            {
                long id=Convert.ToInt64(e.Node.Value);
                var childs = entities.Organizations.Include("ChildOrganizations").FirstOrDefault(i => i.Organization_ID == id).ChildOrganizations;
                e.Node.Nodes.Clear();

                foreach (var item in childs)
                {
                    e.Node.Nodes.Add(new Telerik.Web.UI.RadTreeNode()
                        {
                            Text=item.Organization_Name_AR,
                            Value=item.Organization_ID.ToString(),
                            ExpandMode=Telerik.Web.UI.TreeNodeExpandMode.ServerSide,
                        });
                }
            }
        }
    }
}